package com.nage.utils;

/**
 * 
 * @author http://dbaktiar.wordpress.com/2009/06/26/float-and-byte-array-conversion/
 *
 */

public class ByteArrayBuilder {
	private static final int MASK = 0xff;

	/**
	 * convert byte array (of size 4) to float
	 * @param test
	 * @return
	 */
	public static float byteArrayToFloat(byte test[]) {
		int bits = 0;
		int i = 0;
		for (int shifter = 3; shifter >= 0; shifter--) {
			bits |= ((int) test[i] & MASK) << (shifter * 8);
			i++;
		}

		return Float.intBitsToFloat(bits);
	}
	
	public static double byteArrayToDouble(byte bytes[]) {
		long value = 0;
		for (int i = 0; i < bytes.length; i++)
		{
		   value += (bytes[i] & 0xff) << (8 * i);
		}
		return Double.longBitsToDouble(value);
	}

	/**
	 * convert float to byte array (of size 4)
	 * @param f
	 * @return
	 */
	public static byte[] floatToByteArray(float f) {
		int i = Float.floatToRawIntBits(f);
		return intToByteArray(i);
	}
	
	public static byte[] doubleToByteArray(double d) {
		long l = Double.doubleToRawLongBits(d);
		return longToByteArray(l);
	}

	public static byte[] longToByteArray(long l) {
		return new byte[] {
		        (byte)((l >> 56) & 0xff),
		        (byte)((l >> 48) & 0xff),
		        (byte)((l >> 40) & 0xff),
		        (byte)((l >> 32) & 0xff),
		        (byte)((l >> 24) & 0xff),
		        (byte)((l >> 16) & 0xff),
		        (byte)((l >> 8) & 0xff),
		        (byte)((l >> 0) & 0xff),
		    };
	}

	/**
	 * convert int to byte array (of size 4)
	 * @param param
	 * @return
	 */
	public static byte[] intToByteArray(int param) {
		byte[] result = new byte[4];
		for (int i = 0; i < 4; i++) {
			int offset = (result.length - 1 - i) * 8;
			result[i] = (byte) ((param >>> offset) & MASK);
		}
		return result;
	}

	/**
	 * convert byte array to String.
	 * @param byteArray
	 * @return
	 */
	public static String byteArrayToString(byte[] byteArray) {
		StringBuilder sb = new StringBuilder("[");
		if(byteArray == null) {
			throw new IllegalArgumentException("byteArray must not be null");
		}
		int arrayLen = byteArray.length;
		for(int i = 0; i < arrayLen; i++) {
			sb.append(byteArray[i]);
			if(i == arrayLen - 1) {
				sb.append("]");
			} else{
				sb.append(", ");
			}
		}
		return sb.toString();
	}

	public static float byteArrayToFloat(byte b1, byte b2, byte b3, byte b4) {
		byte[] bytes = new byte[]{b1, b2, b3, b4};
		return byteArrayToFloat(bytes);
	}

	public static double byteArrayToDouble(byte b1, byte b2, byte b3, byte b4,
			byte b5, byte b6, byte b7, byte b8) {
		byte[] bytes = new byte[]{b1, b2, b3, b4, b5, b6, b7, b8};
		return byteArrayToDouble(bytes);
	}


}
